// pages/bid/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    categories:[],
    currentCategory : 0,
    screenHeight : 100,
    page: 1,
    nextPage: true,
    products: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var self = this;
    app.httpGet('/index.php?r=v1/category/index',{
      success: function(res){
        console.log(res)
        if(res.code == 200)
        {
          self.setData({
            categories:res.data
          });
        }
        else
        {
          wx.showToast({
            title: res.msg
          })
        }
      }
    });
    this.loadPage();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  switchCat: function(e){
    console.log(e);
    if(this.data.currentCategory != e.currentTarget.dataset.id)
    {
      this.setData({ 
        currentCategory: e.currentTarget.dataset.id,
        page:1,
        nextPage:true
        });
        this.loadPage();
    }
  },
  loadPage: function () {
    console.log("loadPage");
    var self = this;

    //已经有数据
    if (!self.data.nextPage) {
      console.log("已经是最后一页");
      return;
    }

    console.log(self.data.products);
    console.log("before setdata");

    app.httpGet('/index.php?r=v1/win/index&category_id=' + self.data.currentCategory + '&page=' + self.data.page, {
      success: function (res) {
        console.log(res);
        if (res.data.page < res.data.total_page) {
          self.setData({ nextPage: true });
        }
        else {
          self.setData({ nextPage: false });
        }
        //第一页直接覆盖
        if (self.data.page == 1) {
          self.setData(
            { products: res.data }
          )
        }
        else {
          var oldProducts = self.data.products;
          oldProducts.page = res.data.page;
          oldProducts.total = res.data.total;
          oldProducts.total_page = res.data.total_page;
          oldProducts.items = oldProducts.items.concat(res.data.items);
          self.setData(
            { products: oldProducts }
          )
        }
        console.log(self.data.products);
      }
    });
  }
})